package com.countertack.testcases;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.InetAddress;

import org.doublecloud.vi.vmware.guest.GuestProcessDirector;
import org.json.JSONObject;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.countertack.utils.Configuration;
import com.countertack.utils.HttpClientUtils;
import com.countertack.utils.Utils;
import com.countertack.vmware.VMWareConnector;
import com.countertack.vmware.VMWareUtils;
import com.vmware.vim25.mo.VirtualMachine;

public class FileExtraction {

	public static void main(String[] args) throws Exception {
		StringBuffer testCaseResult = new StringBuffer();
		ImpalaConnector iConnector = null;
		VMWareConnector esxiConnector = null;
		try {

		/*if (args.length <= 0) {

				System.out.println("configuration details missed !");
				return;
			}
			String configFilePath = args[0];*/

			
			 String configFilePath =
			 "C:\\Users\\user\\Desktop\\smoketestautomation\\2kr2\\config.properties"
			 ;
			

			Configuration.loadProperties(configFilePath);
			String sizOfFlToExtract = Configuration
					.getProperty("fileextractionsize");
			String maxSizeOfextFile = Configuration
					.getProperty("fileextractionmaxsize");

			String vmUser = Configuration.getProperty("vmuser");
			String vmPassword = Configuration.getProperty("vmpassword");

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(Configuration
					.getProperty("sentinelehost"));

			InetAddress address = InetAddress.getByName(Configuration
					.getProperty("sentinelehost"));
			String sentenelIp = address.getHostAddress();
			System.out.println(address.getHostAddress());

			esxiConnector = new VMWareConnector(
					Configuration.getProperty("esxi"));
			// poweredOn
			final VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(Configuration
							.getProperty("vmname"));

			// win7x64-sym-2
			System.out.println("power state >>>"
					+ endPointMachine.getRuntime().powerState);

			// System.out.println("VM Ip Address>>>" + vmIp);
			String smokeSnapShotName = Configuration
					.getProperty("rootsnapshotname");
			esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
					.getRootSnapshotList(), smokeSnapShotName);

			System.out.println("Reverting to root snap shot>>>>>"
					+ smokeSnapShotName);

			Thread.sleep(180000);

			esxiConnector.checkAndRunVirtualMachine(endPointMachine);

			String vmIp = Configuration.getProperty("vmip");
			if (vmIp == null || vmIp.trim() == "") {

				vmIp = endPointMachine.getGuest().ipAddress;
			}
			System.out.println("ip>>>" + endPointMachine.getGuest().ipAddress);

			final SSHManager endpointSsh = new SSHManager(vmUser, vmPassword,
					vmIp);
			endpointSsh.connect();
			testCaseResult.append("VM NAME>>>>"
					+ Configuration.getProperty("vmname") + "\n");
			testCaseResult.append("VM IP>>>"
					+ endPointMachine.getGuest().ipAddress + "\n");
			testCaseResult.append("Sentinel  IP>>>" + sentenelIp + "\n");
			boolean isXp = false;

			String osType = VMWareUtils.getVMOSArchitecture(
					Configuration.getProperty("esxi"),
					Configuration.getProperty("vmname"));
			testCaseResult.append("OS>>>>" + osType + "\n");
			if (osType != null) {

				osType = osType.toLowerCase();

				if (osType.contains("xp")) {

					isXp = true;
				}
			}

			// installing agent

			Utils.InstallKernalModuleOnEndpointmachine(endpointSsh, vmUser,
					sentenelIp, isXp);

			// retriving endpoint id
			String eId = null;
			try {
				eId = Utils.getEndpointId(iConnector, vmIp);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Endpoin not installed ");
				return;
			}

			if (eId == null) {

				System.out.println("endpoint not installed");
				return;
			}

			testCaseResult.append("Endpoint ID>>>>" + eId + "\n");

			String kernal_module_version = Utils.getDriverVersion(eId,
					iConnector);
			testCaseResult.append("Kernal Module Version>>>>"
					+ kernal_module_version + "\n");

			Utils.pauseEndpoint(eId);

			Thread.sleep(60000);

			Utils.resumeEndpoint(eId);

			Thread.sleep(60000);

			// creating sample file

			try {
				RandomAccessFile fileTobeext = new RandomAccessFile(
						"fileextractiontest.txt", "rw");
				fileTobeext.setLength(Long.valueOf(sizOfFlToExtract));
				Thread.sleep(30000);
			} catch (Exception e) {

				e.printStackTrace();
			}

			endpointSsh.copyFile("fileextractiontest.txt",
					"fileextractiontest.txt");
			Thread.sleep(60000);

			// remote file size

			String rmFileSize = null;

			if (isXp) {
				rmFileSize = endpointSsh
						.returnCommandOutPut("cmd /c dir /s \"c:\\Documents and Settings\\"
								+ vmUser + "\\fileextractiontest.txt\"");

			} else {

				rmFileSize = endpointSsh
						.returnCommandOutPut("cmd /c dir /s c:\\Users\\"
								+ vmUser + "\\fileextractiontest.txt");

			}
			if (rmFileSize != null) {

				if (rmFileSize.indexOf("1 File(s)") != -1) {
					rmFileSize = rmFileSize.substring(rmFileSize
							.indexOf("1 File(s)") + "1 File(s)".length());
					if (rmFileSize.indexOf("bytes") != -1) {

						rmFileSize = rmFileSize.substring(0,
								rmFileSize.indexOf("bytes"));
						rmFileSize = rmFileSize.trim();

					}
					if (rmFileSize.contains(",")) {

						rmFileSize = rmFileSize.replaceAll(",", "");
						rmFileSize = rmFileSize.trim();

					}

				}
				System.out.println("Remote file size>>>" + rmFileSize);
				testCaseResult
						.append("Remote file size>>>" + rmFileSize + "\n");
			}

			// composing file extraction request
			String fileExtractionPayload = null;
			if (isXp) {
				fileExtractionPayload = "{ \"endpoint\" : \"" + eId
						+ "\", \"path\": \"c:\\\\Documents and Settings\\\\"
						+ vmUser + "\\\\fileextractiontest.txt\"}";

			} else {

				fileExtractionPayload = "{ \"endpoint\" : \"" + eId
						+ "\", \"path\": \"c:\\\\Users\\\\" + vmUser
						+ "\\\\fileextractiontest.txt\"}";

			}

			String fileExtId = Utils.extractFile(fileExtractionPayload);

			if (fileExtId == null) {

				System.out.println("Failed to compose file extraction request");
				testCaseResult
						.append("Failed to compose file extraction request"
								+ "\n");
				return;

			}
			Thread.sleep(120000);

			String fileExtStatus = Utils.getExtractedFileStatus(iConnector,
					fileExtId);

			if (fileExtStatus == null) {

				System.out.println("Unable to retrive file extraction status");
				testCaseResult
						.append("Unable to retrive file extraction status"
								+ "\n");

				return;

			}

			if ("complete".equalsIgnoreCase(fileExtStatus)) {

				System.out.println("FileExtarction Result----->Pass");
				testCaseResult.append("FileExtarction Result----->Pass" + "\n");

			} else {

				System.out.println("FileExtarction Result----->Fail");
				testCaseResult.append("FileExtarction Result----->Fail" + "\n");
				return;
			}

			// downloading extracted file to local machine
			Utils.downloadExtractedFile(sentenelIp, fileExtId);

			// unzipping the extracted file

			Utils.unzipFile(fileExtId + ".zip", fileExtId, "sentinel");

			File f = new File(fileExtId);

			boolean verifyinFile = false;

			if (f.exists()) {

				File[] files = f.listFiles();
				for (File f1 : files) {

					System.out.println("File Name>>>" + f1.getName()
							+ "  Size>>>" + f1.length());
					testCaseResult.append("File Name>>>" + f1.getName()
							+ "  Size>>>" + f1.length() + "\n");

					if (f1.getName().contains(fileExtId)) {
						testCaseResult.append("Extracted file size"
								+ +f1.length() + "\n");
						if (String.valueOf(f1.length()).equalsIgnoreCase(
								rmFileSize)) {
							verifyinFile = true;

						}

					}
				}

			}

			if (verifyinFile) {

				System.out.println("Verifying file extraction------>success");
				testCaseResult.append("Verifying file extraction------>success"
						+ "\n\n\n\n");
			} else {

				System.out.println("Verifying file extraction------>Fail");
				testCaseResult.append("Verifying file extraction------>Fail"
						+ "\n\n\n\n");

			}

			// verifying file extraction with file more than 2 mb

			testCaseResult
					.append("<===================Verifying File Extraction With File More Than "
							+ maxSizeOfextFile
							+ " byte(s) Size==================>" + "\n");

			try {
				RandomAccessFile fileMoreThan2mb = new RandomAccessFile(
						"moreth2mbfile.txt", "rw");
				fileMoreThan2mb.setLength(Long.valueOf(maxSizeOfextFile) + 5);
				Thread.sleep(30000);
			} catch (Exception e) {

				e.printStackTrace();
			}

			endpointSsh.copyFile("moreth2mbfile.txt", "moreth2mbfile.txt");
			Thread.sleep(30000);

			String more2mbfileExtractionPayload = null;
			if (isXp) {
				more2mbfileExtractionPayload = "{ \"endpoint\" : \"" + eId
						+ "\", \"path\": \"c:\\\\Documents and Settings\\\\"
						+ vmUser + "\\\\moreth2mbfile.txt\"}";

			} else {

				more2mbfileExtractionPayload = "{ \"endpoint\" : \"" + eId
						+ "\", \"path\": \"c:\\\\Users\\\\" + vmUser
						+ "\\\\moreth2mbfile.txt\"}";

			}

			String more2mbfileExtId = Utils
					.extractFile(more2mbfileExtractionPayload);

			if (more2mbfileExtId == null) {

				System.out
						.println("Failed to compose file extraction request for more than "
								+ maxSizeOfextFile
								+ " bytes(s) file ##### File extraction id>>"
								+ more2mbfileExtId);
				testCaseResult
						.append("Failed to compose file extraction request for more than "
								+ maxSizeOfextFile
								+ " bytes(s) file ##### File extraction id>>"
								+ more2mbfileExtId + "\n");

			}
			Thread.sleep(120000);

			String moreth2mbfileExtStatus = Utils.getExtractedFileStatus(
					iConnector, more2mbfileExtId);

			if (moreth2mbfileExtStatus == null) {

				System.out
						.println("Unable to retrive file extraction status for more than "
								+ maxSizeOfextFile + " byte(s) file");
				testCaseResult
						.append("Unable to retrive file extraction status for more than "
								+ maxSizeOfextFile + " byte(s) file" + "\n");

			}

			if ("complete".equalsIgnoreCase(moreth2mbfileExtStatus)) {

				System.out
						.println("FileExtarction Result for more than "
								+ maxSizeOfextFile
								+ " byte(s) file ----->Fail  ### File extraction status>>>>>"
								+ moreth2mbfileExtStatus);
				testCaseResult
						.append("FileExtarction Result for more than "
								+ maxSizeOfextFile
								+ " byte(s) file----->Fail ### File extraction status>>>>>"
								+ moreth2mbfileExtStatus + "\n\n\n\n");

			} else {

				System.out
						.println("FileExtarction Result for more than "
								+ maxSizeOfextFile
								+ " byte(s) file----->Pass ### File extraction status>>>>>"
								+ moreth2mbfileExtStatus);
				testCaseResult
						.append("FileExtarction Result for more than "
								+ maxSizeOfextFile
								+ " byte(s) file----->Pass ### File extraction status>>>>>"
								+ moreth2mbfileExtStatus + "\n\n\n\n");
			}

			// verifying file extraction in agent pause state

			testCaseResult
					.append("<===================Verifying File Extraction In Agent Pause State==================>"
							+ "\n");

			Utils.pauseEndpoint(eId);

			Thread.sleep(60000);

			fileExtId = Utils.extractFile(fileExtractionPayload);

			if (fileExtId == null) {

				System.out
						.println("Failed to compose file extraction request in endpoint pause state");
				testCaseResult
						.append("Failed to compose file extraction request in endpoint pause state"
								+ "\n");
				return;

			}
			Thread.sleep(120000);

			fileExtStatus = Utils.getExtractedFileStatus(iConnector, fileExtId);

			if (fileExtStatus == null) {

				System.out
						.println("Unable to retrive file extraction status in endpoint pause state");
				testCaseResult
						.append("Unable to retrive file extraction status in endpoint pause state"
								+ "\n");

				return;

			}

			if ("complete".equalsIgnoreCase(fileExtStatus)) {

				System.out
						.println("FileExtarction Result in endpoint pause state----->Pass");
				testCaseResult
						.append("FileExtarction Result in endpoint pause state----->Pass"
								+ "\n");

			} else {

				System.out
						.println("FileExtarction Result in endpoint pause state----->Fail");
				testCaseResult
						.append("FileExtarction Result in endpoint pause state----->Fail"
								+ "\n");
				return;
			}

			// downloading extracted file to local machine
			Utils.downloadExtractedFile(sentenelIp, fileExtId);

			// unzipping the extracted file

			Utils.unzipFile(fileExtId + ".zip", fileExtId, "sentinel");

			f = new File(fileExtId);

			verifyinFile = false;

			if (f.exists()) {

				File[] files = f.listFiles();
				for (File f1 : files) {

					System.out.println("File Name endpoint pause state>>>"
							+ f1.getName() + "  Size>>>" + f1.length());
					testCaseResult.append("File Name endpoint pause state>>>"
							+ f1.getName() + "  Size>>>" + f1.length() + "\n");

					if (f1.getName().contains(fileExtId)) {
						testCaseResult
								.append("Extracted file size endpoint pause state>>>"
										+ +f1.length() + "\n");
						if (String.valueOf(f1.length()).equalsIgnoreCase(
								rmFileSize)) {
							verifyinFile = true;

						}

					}
				}

			}

			if (verifyinFile) {

				System.out
						.println("Verifying file extraction in endpoint pause state------>success");
				testCaseResult
						.append("Verifying file extraction in endpoint pause state------>success"
								+ "\n");
			} else {

				System.out
						.println("Verifying file extraction in endpoint pause state------>Fail");
				testCaseResult
						.append("Verifying file extraction in endpoint pause state------>Fail"
								+ "\n");

			}

			Utils.resumeEndpoint(eId);

		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();

				}
			} catch (Exception e) {

				e.printStackTrace();
			}
			try {

				if (esxiConnector != null) {
					esxiConnector.closeEsxiConnection();
				}

			} catch (Exception e) {

				e.printStackTrace();
			}
			Utils.addResultsToLog(testCaseResult, "file_extraction",
					Configuration.getProperty("vmname"));
		}

	}

}
